<template>
  <div class="order-outer">
    <div class="order">
      <div class="checkout-wrap">
        <div class="checkout-main">
          <div class="checkout-detail">
            <!-- 详情-地址 -->
            <div class="detail-section address-detail">
              <div class="address-header">
                <span class="header-title">收货地址</span>
              </div>
              <div
                class="address-list"
                @click="changeAddressActive">
                <div
                  class="address-item"
                  :style="{
                    'border-color':
                      address.address_id === +address_id
                        ? '#ff6900'
                        : ' #e0e0e0'
                  }"
                  v-for="address of addressList"
                  :key="address.address_id"
                  :data-id="address.address_id">
                  <i
                    class="iconfont"
                    @click="delAddress(address.address_id)">
                    ×
                  </i>
                  <div class="address-info">
                    <div class="name">
                      {{ address.address_name }}
                      <span style="color: rgb(176, 176, 176)"></span>
                    </div>
                    <div class="tel">{{ usePhone(address.address_phone) }}</div>
                    <div class="address-con">
                      <span>{{ address.province_name }}</span>
                      <span>{{ address.city_name }}</span>
                      <span>{{ address.county_name }}</span>
                      <span>{{ address.way_name }}</span>
                      <span class="info">{{ address.address_detail }}</span>
                    </div>
                    <div class="address-action">
                      <span @click="modAddress(address)">修改</span>
                    </div>
                  </div>
                  <div
                    class="address-info-solt"
                    style="display: none"></div>
                </div>
                <div
                  @click="modAddress()"
                  class="address-item"
                  v-if="
                    showMoreList && addressStore.userAddressList.length > 3
                  ">
                  <div class="add-desc">
                    <i class="iconfont">+</i>
                    <span>添加新地址</span>
                  </div>
                </div>
                <div
                  @click="changeShowMoreList"
                  class="more-btn"
                  v-if="showMoreBtn">
                  <span>
                    显示更多地址
                    <img
                      :style="{
                        transform: showMoreList
                          ? ' rotate(90deg)'
                          : ' rotate(-90deg)'
                      }"
                      class="iconfont-normal"
                      :src="require('@/asset/img/arrow-right-#333.png')" />
                  </span>
                </div>
              </div>
            </div>
            <!-- 详情-商品 -->
            <div class="detail-section">
              <div class="detail-header">商品及优惠券</div>
              <div class="goods-list">
                <div
                  class="good-item"
                  v-for="goods in goodsInfos">
                  <div class="item-desc good-img">
                    <img v-lazyload="goods.goods_image" />
                  </div>
                  <div class="item-desc good-name">
                    <a
                      href="//www.mi.com/buy?product_id=1192100011"
                      target="_blank">
                      <span>
                        {{
                          `${goods.goods_name} ${goods.goods_version} ${goods.goods_color}`
                        }}
                      </span>
                    </a>
                  </div>
                  <div class="item-desc price-box">
                    <div class="item-desc good-price">
                      {{ `${goods.goods_price}元 x ${goods.goods_count}` }}
                    </div>
                    <div class="item-desc good-status"></div>
                    <div class="item-desc good-total">
                      {{ `${goods.goods_price * goods.goods_count}元` }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 详情-方式,发票 -->
            <div class="detail-section">
              <!-- 详情-配送方式 -->
              <div class="section-options section-shipment">
                <div class="options-desc options-header">
                  <div class="title">配送方式</div>
                </div>
                <div class="options-desc options-body">
                  <div class="options-list">
                    <div class="options-item">
                      {{
                        `${totalPrice > 69 ? '包邮' : '快递配送（运费 10 元）'}`
                      }}
                    </div>
                  </div>
                </div>
              </div>
              <!-- 详情-发票 -->
              <div class="section-options section-invoice">
                <div class="options-desc options-header">
                  <div class="title">发票</div>
                </div>
                <div class="options-desc options-body">
                  <div class="options-list">
                    <div class="options-item">电子普通发票</div>
                    <div class="options-item">个人</div>
                    <div class="options-item">商品明细</div>
                    <div class="options-item">修改 &gt;</div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 详情-收费 -->
            <div class="detail-section count-detail">
              <div class="section-discount">
                <div class="discount-coupon">
                  <a
                    href="javascript:;"
                    class="coupon-title">
                    <i class="iconfont">+</i>
                    <span>使用优惠券</span>
                    <span class="available-coupon-tip">无可用</span>
                  </a>
                </div>
                <div class="discount-coupon">
                  <a
                    href="javascript:;"
                    class="coupon-title">
                    <i class="iconfont">+</i>
                    <span>使用小米礼品卡</span>
                  </a>
                </div>
              </div>
              <div class="section-bill">
                <div class="bill-item">
                  <div class="bill-name">商品件数：</div>
                  <div class="bill-money">{{ totalNum }}件</div>
                </div>
                <div class="bill-item">
                  <div class="bill-name">商品总价：</div>
                  <div class="bill-money">{{ totalPrice }}元</div>
                </div>
                <div class="bill-item">
                  <div class="bill-name">活动优惠：</div>
                  <div class="bill-money">-0元</div>
                </div>
                <div class="bill-item">
                  <div class="bill-name">优惠券抵扣：</div>
                  <div class="bill-money">-0元</div>
                </div>
                <div class="bill-item">
                  <div class="bill-name">运费：</div>
                  <div class="bill-money">{{ totalPrice > 69 ? 0 : 10 }}元</div>
                </div>
                <div class="bill-item total-price">
                  <div class="bill-name">应付总额：</div>
                  <div class="bill-money">
                    <em>{{ allPrice }}</em>
                    元
                  </div>
                </div>
              </div>
            </div>
            <!-- 详情-footer -->
            <div class="detail-section footer-detail clearfix">
              <div class="footer-address">
                <div
                  class="selecter-address"
                  v-if="address_id !== 0">
                  <div class="address-name">{{ addressNow?.name }}</div>
                  <div class="address-desc">
                    <span>{{ addressNow?.desc }}</span>
                    <a>&nbsp;修改</a>
                  </div>
                </div>
              </div>
              <div class="handle-action">
                <div class="operating-button">
                  <Button
                    :style="{
                      height: 40 + 'px',
                      width: 160 + 'px',
                      'margin-right': 25 + 'px',
                      'background-color': '#fff'
                    }">
                    返回购物车
                  </Button>
                  <Button
                    @click="toPay"
                    :type="'primary'"
                    :style="{
                      height: 40 + 'px',
                      width: 160 + 'px'
                    }">
                    去结算
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <Transition>
    <Dialog
      v-if="showDialog"
      :changeShowDialog="changeShowDialog"></Dialog>
  </Transition>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { ComputedRef, Ref } from 'vue'
import { useRouter } from 'vue-router'
import useStore from '@/store'
import useGoodsInfos from '@/hooks/useGoodsinfos'
import usePhone from '@/hooks/usePhone'
import useOrderNum from '@/hooks/useOrderNum'
import useCountDown from '@/hooks/useCountDown'
import { userAddress } from '@/model/addressModel'
import { order } from '@/model/orderModel'
import Dialog from '@/components/dialog/index.vue'
import Button from '@/components/button/index.vue'
const { addressStore, userStore, cartStore, orderStore } = useStore()
const router = useRouter()
addressStore.searchAddressListByUserId(userStore.userInfo!.user_id, 1, 9999)
const { addressArr } = addressStore
const addressList = computed(() => {
  return !showMoreList.value
    ? addressStore.userAddressList.slice(0, 4)
    : addressStore.userAddressList
})
const address_id = ref<number>(0)
const changeAddressActive = (e: MouseEvent) => {
  const div = (e as any).path.filter(
    (item: HTMLElement) => item.className === 'address-item'
  )
  if (div.length > 0 && div[0].dataset.id) {
    address_id.value = div[0].dataset.id
    const address = addressStore.userAddressList.filter(
      item => item.address_id === +div[0].dataset.id
    )
    if (address.length > 0) {
      ;(addressArr.id = address[0].address_id),
        (addressArr.name = address[0].address_name),
        (addressArr.phone = address[0].address_phone),
        (addressArr.province = address[0].province_name),
        (addressArr.city = address[0].city_name),
        (addressArr.county = address[0].county_name),
        (addressArr.way = address[0].way_name),
        (addressArr.detail = address[0].address_detail)
    }
  }
}
const addressNow = computed(() => {
  if (address_id.value !== 0) {
    return {
      name: `${addressArr.name} ${usePhone(addressArr.phone)}`,
      desc: `${addressArr.province} ${addressArr.city} ${addressArr.county} ${addressArr.detail}`
    }
  } else {
    return null
  }
})
const showDialog = ref<boolean>(false)
const changeShowDialog = () => {
  showDialog.value = !showDialog.value
}
const modAddress = (address?: userAddress) => {
  address && (addressStore.userAddress = { ...address })
  changeShowDialog()
}
const delAddress = (id: number) => {
  addressStore.delAddress(id)
}
const showMoreList = ref<boolean>(false)
const changeShowMoreList = () => {
  showMoreList.value = !showMoreList.value
  showMoreList.value
    ? addressStore.searchAddressListByUserId(
        userStore.userInfo!.user_id,
        1,
        9999
      )
    : addressStore.searchAddressListByUserId(userStore.userInfo!.user_id, 1)
}
const showMoreBtn = ref<boolean>()
watch(
  () => addressStore.userAddressList.length,
  (newValue, oldValue) => {
    const flag = addressStore.userAddressList.length > 3
    showMoreBtn.value = flag ? true : false
  }
)
let goodsInfos = ref()
let totalNum: Ref<number>
let totalPrice: Ref<number>
let allPrice: ComputedRef<number>
watch(
  () => cartStore.cartArr,
  async (newValue, oldValue) => {
    if (newValue && newValue!.length > 0) {
      goodsInfos.value = (await useGoodsInfos()).value
      let total: number = 0
      let price: number = 0
      goodsInfos.value.forEach((item: any) => {
        total += item.goods_count
        price += item.goods_count * item.goods_price
      })
      totalNum = ref<number>(total)
      totalPrice = ref<number>(price)
      allPrice = computed<number>(() => {
        return totalPrice.value > 69 ? totalPrice.value : totalPrice.value + 10
      })
    }
  },
  { immediate: true }
)
const toPay = () => {
  if (addressNow.value) {
    const goodsList: string[] = []
    goodsInfos.value.forEach((item: any) => {
      const goodsMsg = `${item.goods_name} ${item.goods_version} ${item.goods_color}`
      goodsList.push(goodsMsg)
    })
    const user_id = userStore.userInfo!.user_id
    const orderNum = useOrderNum(user_id)
    sessionStorage.setItem(
      'orderMsg',
      JSON.stringify({
        orderNum,
        addressMsg: `${addressNow.value.name} ${addressNow.value.desc}`,
        goodsList,
        totalPrice: totalPrice.value
      })
    )
    const orderList: order[] = []
    goodsInfos.value.forEach((goodsInfo: any) => {
      const goodsMsg = {
        order_num: orderNum,
        user_id,
        goods_count: goodsInfo.goods_count,
        goodsInfo_id: goodsInfo.goodsInfo_id,
        address_id: address_id.value
      }
      orderList.push(goodsMsg)
    })
    useCountDown.setCountDown(orderNum)
    cartStore.delCartAll(user_id)
    orderStore.addOrder(orderList)
    router.push('confirm')
  }
}
</script>

<style lang="less" scoped>
.v-enter-active,
.v-leave-active {
  transition: 0.5s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}

.order-outer {
  background-color: #f5f5f5;
  padding: 40px 0 60px;
  .order {
    margin: 0 auto;
    width: 1226px;
    background-color: #fff;
    .checkout-wrap {
      .checkout-main {
        .checkout-detail {
          position: relative;
          padding: 48px 0 0;
          .detail-section {
            position: relative;
            padding: 0 24px;
            .detail-header {
              color: #333;
              font-size: 18px;
              line-height: 40px;
            }
            // 商品
            .goods-list {
              padding: 5px 0;
              border-bottom: 1px solid #e0e0e0;
              .good-item {
                position: relative;
                padding: 15px 0;
                .item-desc {
                  display: inline-block;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  line-height: 1;
                  color: #424242;
                  vertical-align: middle;
                }
                .good-img {
                  width: 30px;
                  height: 30px;
                  margin: 0 10px 0 0;
                  img {
                    width: 30px;
                    height: 30px;
                  }
                }
                .good-name {
                  width: 650px;
                  a {
                    color: #424242;
                  }
                }
                .price-box {
                  .good-price {
                    width: 150px;
                    text-align: center;
                  }
                  .good-status {
                    width: 100px;
                    text-align: center;
                  }
                  .good-total {
                    width: 190px;
                    text-align: right;
                    color: #ff6700;
                  }
                }
              }
            }
            .section-options {
              padding: 25px 0;
              border-bottom: 1px solid #e0e0e0;
              .options-desc {
                display: inline-block;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
              .options-header {
                width: 150px;
                .title {
                  color: #333;
                  font-size: 18px;
                  line-height: 38px;
                }
              }
              .options-body {
                .options-list {
                  width: 960px;
                  .options-item {
                    display: inline-block;
                    height: 38px;
                    line-height: 38px;
                    margin-right: 14px;
                    border: 1px solid #fff;
                    color: #ff6700;
                  }
                }
              }
            }
            // 发票
            .section-invoice {
              border: none;
            }
          }
          // 地址
          .address-detail {
            .address-header {
              margin: 0 0 20px;
              .header-title {
                color: #333;
                font-size: 18px;
                line-height: 20px;
              }
            }
            .address-list {
              .address-item {
                display: inline-block;
                width: 268px;
                height: 178px;
                border: 1px solid #e0e0e0;
                cursor: pointer;
                position: relative;
                margin-right: 17px;
                margin-bottom: 20px;
                vertical-align: top;
                transition: all 0.4s ease;
                &:hover .address-info .address-action {
                  opacity: 1;
                }
                > .iconfont {
                  font-size: 24px;
                  position: absolute;
                  top: 0px;
                  right: 10px;
                  color: #b0b0b0;
                  transition: 0.3s;
                  &:hover {
                    color: #333;
                  }
                }
                .address-info {
                  line-height: 22px;
                  color: #757575;
                  padding: 15px 24px 0;
                  .name {
                    font-size: 18px;
                    color: #333;
                    line-height: 30px;
                    margin-bottom: 10px;
                    span {
                      float: right;
                      font-size: 14px;
                      color: #757575;
                    }
                  }
                  .address-con {
                    span {
                      display: inline-block;
                      margin-right: 3px;
                      word-wrap: break-word;
                    }
                    .info {
                      display: inline-block;
                      margin-right: 3px;
                      word-wrap: break-word;
                      width: 100%;
                    }
                  }
                  .address-action {
                    text-align: right;
                    position: absolute;
                    right: 24px;
                    bottom: 10px;
                    transition: 0.3s;
                    opacity: 0;
                    span {
                      color: #ff6700;
                      margin-left: 10px;
                    }
                  }
                }
                .add-desc {
                  position: absolute;
                  top: 50%;
                  left: 50%;
                  transform: translate3d(-50%, -50%, 0);
                  color: #b0b0b0;
                  .iconfont {
                    display: block;
                    width: 30px;
                    height: 30px;
                    margin: 0 auto 8px;
                    font-size: 30px;
                    line-height: 30px;
                    background-color: #e0e0e0;
                    border-radius: 17px;
                    text-align: center;
                    transition: all 0.4s ease;
                    color: #fff;
                  }
                }
              }
              .more-btn {
                margin-bottom: 30px;
                height: 50px;
                line-height: 50px;
                background-color: #eee;
                color: #424242;
                text-align: center;
                cursor: pointer;
                .iconfont-normal {
                  display: inline-block;
                  margin-left: 3px;
                  position: relative;
                  top: -1px;
                  font-size: 14px;
                  vertical-align: middle;
                  // transform: rotate(-90deg);
                }
              }
            }
            .less-list {
              height: 255px;
            }
          }
          // 金额详情
          .count-detail {
            position: relative;
            min-height: 200px;
            padding: 20px 0;
            margin: 0 48px;
            .section-discount {
              position: absolute;
              left: 0;
              top: 20px;
              .discount-coupon {
                position: relative;
                .coupon-title {
                  display: flex;
                  align-items: center;
                  height: 50px;
                  line-height: 50px;
                  cursor: pointer;
                  &:hover {
                    color: #ff6700;
                  }
                  .iconfont {
                    position: relative;
                    display: inline-block;
                    margin: 0 10px 0 0;
                    width: 22px;
                    height: 22px;
                    border-radius: 11px;
                    vertical-align: middle;
                    font-size: 22px;
                    line-height: 1;
                    color: #fff;
                    text-align: center;
                    background-color: #ff6700;
                  }
                  .available-coupon-tip {
                    color: #999;
                    margin: 0 0 0 15px;
                  }
                }
              }
            }
            .section-bill {
              position: absolute;
              right: 0;
              bottom: 20px;
              .bill-item {
                position: relative;
                padding-left: 126px;
                line-height: 2;
                text-align: right;
                .bill-name {
                  position: absolute;
                  top: 0;
                  left: 0;
                  width: 126px;
                  white-space: nowrap;
                  color: #757575;
                }
                .bill-money {
                  color: #ff6700;
                  em {
                    font-size: 30px;
                    line-height: 1;
                  }
                }
              }
              .total-price {
                margin: 10px 0 0;
                .bill-name {
                  margin-top: 5px;
                }
              }
            }
          }
          // footer
          .footer-detail {
            padding: 20px 48px;
            border-top: 2px solid #f5f5f5;
            position: relative;
            .footer-address {
              float: left;
              .selecter-address {
                line-height: 20px;
                color: #424242;
                .address-desc {
                  a {
                    color: #ff6700;
                    cursor: pointer;
                  }
                }
              }
            }
            .handle-action {
              float: right;
            }
          }
        }
      }
    }
  }
}
</style>
